import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy import signal 
import re

def sin_wave(A, f, fs, phi, t):
    '''
    :params A:    振幅
    :params f:    信号频率
    :params fs:   采样频率
    :params phi:  相位
    :params t:    时间长度
    '''
    # 若时间序列长度为 t=1s, 
    # 采样频率 fs=1000 Hz, 则采样时间间隔 Ts=1/fs=0.001s
    # 对于时间序列采样点个数为 n=t/Ts=1/0.001=1000, 即有1000个点,每个点间隔为 Ts
    Ts = 1/fs
    n = t / Ts
    n = np.arange(n)
    y = A*np.sin(2*np.pi*f*n*Ts + phi*(np.pi/180))
    return y

def round_signal(src_signal, round_bit):
	rd_signal = np.array([], dtype='int')
	normalize = max(abs(src_signal))
	for val in src_signal:
		signal_temp = round(val/normalize*(2**(round_bit-1)-1)) #比特量化
		rd_signal = np.append(rd_signal, signal_temp)
	return rd_signal


def round_bin_signal(src_signal, round_bit):
	bin_signal = np.array([], dtype = 'str')
	normalize = max(abs(src_signal))
	for val in src_signal:
		signal_temp = round((val/normalize) * (2**(round_bit-1)-1)) #比特量化
		if signal_temp < 0 :
			signal_temp = signal_temp + 2**round_bit #2‘s的特性，相反数相加等于位宽
		signal_temp = f"{signal_temp:0{round_bit}b}"
		bin_signal = np.append(bin_signal, signal_temp)
	return bin_signal

#读取二进制文件时进行转换
def load_bin_signal(src_signal, round_bit):
	_list = []
	for i in src_signal:
		if i == '\n':
			continue
		else:
			temp_val = int(i ,2)
			if i[0] == '1':
				temp_val = temp_val -  2**16
			_list.append(temp_val)
	return _list


# 50hz 200hz combination signal
fs = 5000
t1 = 1
hz_50 = sin_wave(A=1, f=50, fs=fs, phi=0, t=t1)
hz_500 = sin_wave(A=1, f=500, fs=fs, phi=0, t=t1)
signal_com = hz_50 + hz_500
x = np.arange(0, t1, 1/fs)

# #使用正态噪声
# signal_noise = hz_50 + 1*np.random.rand(int(t1*fs)) //不清楚确切幅值，不可直接使用LMS

# a = round_bin_signal(signal_com ,16)
# with open("excitation_signal.txt", "w") as f:
# 	for i in range(len(a)):
# 		if i == 0:
# 			f.write(str(a[i]))
# 		else:
# 			f.write('\n'+str(a[i]))

# b = round_bin_signal(hz_50, 16)
# with open("expect_signal.txt", "w") as f:
# 	for i in range(len(b)):
# 		if i == 0:
# 			f.write(str(b[i]))
# 		else:
# 			f.write('\n'+str(b[i]))



with open('excitation_signal.txt', 'r') as f:
	excitation_signal = f.readlines()

with open('expect_signal.txt', 'r') as f:
	expect_signal = f.readlines()

with open('response_signal.txt', 'r') as f:
	response_signal = f.readlines()



excitation_signal_list = load_bin_signal(excitation_signal, 16)
expect_signal_list = load_bin_signal(expect_signal, 16)
response_signal_list = [int(i) for i in response_signal]



plt.figure(1)
plt.subplot(3,1,1)
plt.plot(x, excitation_signal_list, 'k')
plt.axis([0, 0.2, -5e4, 5e4])
plt.xlabel("Time(s)")
plt.ylabel("Amplitude")
plt.title('excitation in time domain')
plt.subplot(3,1,3)
plt.plot(x, abs(fft(excitation_signal_list)), 'b--')
plt.xlabel("Frequency(hz)")
plt.ylabel("|P(f)|")
plt.title('excitation in frequency domain')



plt.figure(2)
plt.subplot(3,1,1)
plt.plot(x, expect_signal_list, 'r-.')
plt.axis([0, 0.2, -5e4, 5e4])
plt.xlabel("Time(s)")
plt.ylabel("Amplitude")
plt.title('expect in time domain')
plt.subplot(3,1,3)
plt.plot(x, abs(fft(expect_signal_list)), 'b--')
plt.xlabel("Frequency(hz)")
plt.ylabel("|P(f)|")
plt.title('expect in frequency domain')

y = np.arange(0, t1, 1/len(response_signal_list))
plt.figure(3)
plt.subplot(3,1,1)
plt.plot(y, response_signal_list, 'g--')
plt.axis([0.960, 0.970, -1e9, 1e9])
plt.xlabel("Time(s)")
plt.ylabel("Amplitude")
plt.title('50_hz in time domain')
plt.subplot(3,1,3)
plt.plot(y, abs(fft(response_signal_list)), 'b--')
plt.xlabel("Frequency(hz)")
plt.ylabel("|P(f)|")
plt.title('50_hz in frequency domain')
#plt.legend(['phase 0', 'phase 30', 'phase 60', 'phase 90'], loc=1)

plt.show()

